const fs = require('fs');
const clc = require('cli-color');

const getIndexJsxText = (pageName) => {
    const indexJsx = `import React, { Component } from 'react';
import './index.less';

class ${pageName} extends Component {
    constructor(props) {
        super(props);
        this.state = {}
    }

    render() {

    }

    componentDidMount() {

    }
}

export default ${pageName};
`;
    return indexJsx;
}

const writeIndexJsx = (pageName) => {
    return new Promise((resolve, reject) => {
        fs.writeFile(`./src/pages/${pageName}/index.jsx`, getIndexJsxText(pageName), 'utf8', (err) => {
            if (err) {
                reject(err);
            } else {
                resolve(true);
            }
        });
    });
}

const writeIndexLess = (pageName) => {
    return new Promise((resolve, reject) => {
        fs.writeFile(`./src/pages/${pageName}/index.less`, '', 'utf8', (err) => {
            if (err) {
                reject(err);
            } else {
                resolve(true);
            }
        });
    });
}

const mkdir = (pageName) => {
    return new Promise((resolve, reject) => {
        fs.mkdir(`./src/pages/${pageName}`, (err) => {
            if (err) {
                reject(err);
            } else {
                resolve(true);
            }
        })
    })
}

const writePage = async (pageName) => {
    await mkdir(pageName);
    await writeIndexJsx(pageName);
    await writeIndexLess(pageName);
}

const readPages = async () => {
    return new Promise((resolve, reject) => {
        fs.readdir('./src/pages/', (err, dirs) => {
            if (err) {
                reject(err);
            } else {
                resolve(dirs);
            }
        })
    });
}

const readRouteConfig = () => {
    return new Promise((resolve, reject) => {
        fs.readFile('./src/router/config.js', 'utf8', (err, data) => {
            if (err) {
                reject(err);
            } else {
                resolve(data);
            }
        })
    })
}

const wirteRouterConfig = (fileContent) => {
    return new Promise((resolve, reject) => {
        fs.writeFile('./src/router/config.js', fileContent, 'utf8', (err) => {
            if (err) {
                reject(err);
            } else {
                resolve(true);
            }
        })
    })
}

(async () => {
    try {
        const pages = await readPages();

        const argvs = process.argv;
        if (argvs.length < 3) {
            console.log(clc.bgRed('Please Set Page Name'));
            process.exit(0);
        }

        const pageName = argvs[2];

        if (pages.includes(pageName)) {
            console.log(clc.bgRed(`Page ${pageName} Already Has`));
            process.exit(0);
        }

        await writePage(pageName);

        console.log(clc.bgGreen(`create page ${pageName} success`));

        const text = await readRouteConfig();

        const routerPreg = /\[\{([\s\S]*)]/;

        const routerJsonText = routerPreg.exec(text)[0];

        // ummmm ugly!!
        // ====== 追加 route
        let arr = routerJsonText.split('},');
        arr.pop();
        const routerConfig = ` {
        path: '/${pageName}',
        exact: true,
        authRules: false,
        component: ${pageName},
        `;
        arr.push(routerConfig);
        
        arr.push('\n    ]');

        let s = text.replace(routerJsonText, arr.join('},'));
        let newFile = s.replace('        },', '    },')

        // ====== 追加 import

        let arr2 = newFile.split('\n\n\n');
        arr2[0] += `\n\nimport ${pageName} from '../pages/${pageName}';`;
        let finsh = arr2.join('\n\n\n');
        await wirteRouterConfig(finsh);
        
        console.log('');

        console.log(clc.bgGreen(`route config update success`));
    } catch (error) {
        console.log(error);
        process.exit(0)
    }
})()